package com.wzj.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.wzj.yygh.common.exception.YyghException;
import com.wzj.yygh.common.result.ResultCode;
import com.wzj.yygh.enums.OrderStatusEnum;
import com.wzj.yygh.enums.PaymentTypeEnum;
import com.wzj.yygh.enums.RefundStatusEnum;
import com.wzj.yygh.model.order.OrderInfo;
import com.wzj.yygh.model.order.PaymentInfo;
import com.wzj.yygh.model.order.RefundInfo;
import com.wzj.yygh.order.service.OrderService;
import com.wzj.yygh.order.service.PaymentService;
import com.wzj.yygh.order.service.RefundInfoService;
import com.wzj.yygh.order.service.WeixinService;
import com.wzj.yygh.order.utils.ConstantPropertiesUtils;
import com.wzj.yygh.order.utils.HttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ConstantPropertiesUtils constantPropertiesUtils;
    @Autowired
    private PaymentService paymentService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundInfoService refundInfoService;

    //生成微信支付二维码
    @Override
    public boolean createNative(Long orderId) {
        OrderInfo orderInfo = orderService.getOrderInfoByOrderId(orderId);
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        boolean flag = orderService.updateById(orderInfo);
        return flag;
    }


    //调用微信接口实现支付状态查询
    @Override
    public boolean queryPayStatus(Long orderId) {
        try {
            //1 根据orderId获取订单信息
            OrderInfo orderInfo = orderService.getById(orderId);
            //2 封装提交参数
//            Map<String,String> paramMap = new HashMap<>();
//            paramMap.put("appid", constantPropertiesUtils.getAppid());
//            paramMap.put("mch_id", constantPropertiesUtils.getPartnerkey());
//            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
//            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

            //3 设置请求内容
//            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
//            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,constantPropertiesUtils.getPartnerkey()));
//            client.setHttps(true);
//            client.post();

            //4 得到微信接口返回数据
//            String xml = client.getContent();
//            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
//            if("FAIL".equals(resultMap.get("return_code")) || "FAIL".equals(resultMap.get("result_code"))) {
//                throw new YyghException(resultMap.get("err_code")+": "+resultMap.get("err_code_des"),ResultCode.ERROR);
//            }
//            System.out.println("支付状态resultMap:"+resultMap);
            //验签
            //5 把接口数据返回
//            if ("SUCCESS".equals(resultMap.get("trade_state"))){
                //更新订单状态
                orderService.updateStatusById(orderId, OrderStatusEnum.PAID.getStatus());
                //记录支付日志
                paymentService.savePaymentInfo(orderInfo);
                //调用医院端的接口修改医院端的订单状态
//                HashMap<String, Object> paramsMap = new HashMap<>();
//                paramsMap.put("hoscode",orderInfo.getHoscode());
//                paramsMap.put("hosRecordId",orderInfo.getHosRecordId());
//                paramsMap.put("timestamp", HttpRequestHelper.getTimestamp());
//
//                String signKey = "acc13df8dc5fb4845c2a4c8d9da7fe11";
//                paramsMap.put("sign",HttpRequestHelper.getSign(paramsMap,signKey));
//
//                String url = "http://localhost:9998/order/updatePayStatus";
//                JSONObject result = HttpRequestHelper.sendRequest(paramsMap, url);
//                if (result.getInteger("code") != 200) {
//                    throw new YyghException("查单失败",ResultCode.ERROR);
//                }
                return true;
//            }
        }catch (YyghException e){
            throw e;
        }catch (Exception e) {
            throw new YyghException(ResultCode.ERROR,"查单失败",e);
        }
    }

    //微信退款
    @Override
    public void refund(Long orderId) {
        try {
            //获取支付记录信息
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            //添加信息到退款记录表
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
            //判断当前订单数据是否已经退款
            if(refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return;
            }
            //调用微信接口实现退款
            //封装需要参数
            Map<String,String> paramMap = new HashMap<>();
            paramMap.put("appid",constantPropertiesUtils.getAppid());       //公众账号ID
            paramMap.put("mch_id",constantPropertiesUtils.getPartner());   //商户编号
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
//       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
//       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee","1");
            paramMap.put("refund_fee","1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap,constantPropertiesUtils.getPartnerkey());
            //设置调用接口内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            //设置证书信息
            client.setCert(true);
            client.setCertPassword(constantPropertiesUtils.getPartner());
            client.post();

            //接收返回数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if (WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("return_code")) && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
            }else {
                log.error("申请退款失败 - "+xml);
                throw new YyghException("申请退款失败",20304);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
